<?php
/**
 * Auto Complete on a contact email
 *
 * @package Hive\Contact
 * @author Xavier VILAIN
 * @license
 */

use Fox\SearchEngine;
use Hive\Ressource;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Connection;

$xview = Xview::instance();
$final = array();
$term = utf8_decode(Xview::instance()->val('q'));
$term = strtolower(SearchEngine::cleanupContent($term));
$term = str_replace(array('-',' '),'%',$term);
$terms = '%'.$term.'%';
$data = array();
$infos = Fox\Dao::infos(Ressource::className());
$query = $infos->handle()->createQueryBuilder();
$query->select('t.ressource_id as id','t.last_name','t.first_name','t.email AS email','ad.email1 AS email1')
				->from('ressources','t')
				->leftJoin('t','address','ad','t.adrid = ad.adrid')
				->setMaxResults(10);
				
$fragment = new \Fox\Dao\SqlFragment('t.loekz = 0 AND (t.last_name LIKE ? OR t.first_name LIKE ? OR t.email LIKE ? OR ad.email1 LIKE ? )',
					array($terms,$terms,$terms,$terms));
$result = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $data) {
	$label = $data['first_name'].' '.$data['last_name'];
	if(!empty($data['email1'])) {
		$final[] = array('id' => $data['email'].':'.$data['id'],'name' => $data['email']);
		$final[] = array('id' => $data['email1'].':'.$data['id'],'name' => $data['email1']);
	} else {
		$final[] = array('id' => $data['email'].':'.$data['id'],'name' => $label);
	}
}
echo json_encode($final);